// 定义缓存接口
interface Cache {
    set(key: string, value: string): void;
    get(key: string): string | null;
    setJSON<T>(key: string, jsonValue: T): void;
    getJSON<T = any>(key: string): T | null;
    remove(key: string): void;
  }
  
  // 会话级缓存
  const sessionCache: Cache = {
    set(key: string, value: string) {
      if (typeof sessionStorage !== 'undefined') {
        if (key != null && value != null) {
          sessionStorage.setItem(key, value);
        }
      }
    },
    get(key: string) {
      if (typeof sessionStorage !== 'undefined') {
        if (key != null) {
          return sessionStorage.getItem(key);
        }
      }
      return null;
    },
    setJSON<T>(key: string, jsonValue: T) {
      if (jsonValue != null) {
        this.set(key, JSON.stringify(jsonValue));
      }
    },
    getJSON<T = any>(key: string): T | null {
      const value = this.get(key);
      if (value != null) {
        return JSON.parse(value) as T;
      }
      return null;
    },
    remove(key: string) {
      if (typeof sessionStorage !== 'undefined') {
        sessionStorage.removeItem(key);
      }
    }
  };
  
  // 本地缓存
  const localCache: Cache = {
    set(key: string, value: string) {
      if (typeof localStorage !== 'undefined') {
        if (key != null && value != null) {
          localStorage.setItem(key, value);
        }
      }
    },
    get(key: string) {
      if (typeof localStorage !== 'undefined') {
        if (key != null) {
          return localStorage.getItem(key);
        }
      }
      return null;
    },
    setJSON<T>(key: string, jsonValue: T) {
      if (jsonValue != null) {
        this.set(key, JSON.stringify(jsonValue));
      }
    },
    getJSON<T = any>(key: string): T | null {
      const value = this.get(key);
      if (value != null) {
        return JSON.parse(value) as T;
      }
      return null;
    },
    remove(key: string) {
      if (typeof localStorage !== 'undefined') {
        localStorage.removeItem(key);
      }
    }
  };
  
  export default {
    /**
     * 会话级缓存
     */
    session: sessionCache,
    /**
     * 本地缓存
     */
    local: localCache
  };